package com.cby.operation.anti.ui

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.text.Html
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.cby.operation.anti.AntiAddictManager
import com.cby.operation.anti.AntiHeartManager
import com.cby.operation.anti.bean.PopConfigBean
import com.cby.operation.common.ext.getDrawableId
import com.cby.operation.common.ext.getId
import com.cby.operation.common.ext.showToast
import com.cby.operation.common.ui.BaseDialogFragment
import com.cby.operation.common.util.CbyLogUtils
import com.cby.operation.common.util.FastClickUtils
import com.cby.operation.common.util.StringUtils
import com.cby.operation.common.util.WebUtils
import com.cby.operation.sdk.*
import com.cby.operation.sdk.util.HykbAppUtils

/**
 * Description:HykbAntiDialogFragment
 *
 * @author 陈宝阳
 * @create 2020/8/4 11:04
 */
class AntiDialogFragment : BaseDialogFragment() {

    private lateinit var publicPolicyTv: TextView
    private lateinit var warmTipTv: TextView
    private lateinit var detailTv: TextView
    private lateinit var negativeBtn: Button
    private lateinit var positiveBtn: Button
    private lateinit var btnLineView: View
    private var configBeans: ArrayList<PopConfigBean>? = null
    private lateinit var configBean: PopConfigBean
    private var floatConfigBean: PopConfigBean? = null
    private var nick: String? = null
    private var uid: String? = null
    private var loginType: String? = null

    fun update(
        configBeans: List<PopConfigBean>?, nick: String?,
        uid: String?, loginType: String?
    ) {
        this.configBeans!!.clear()
        this.configBeans!!.addAll(configBeans!!)
        this.nick = nick
        this.uid = uid
        this.loginType = loginType
        setContent()
        initListener()
    }

    override fun parseArgs() {
        uid = arguments.getString(KEY_UID)
        nick = arguments.getString(KEY_NICK)
        loginType = arguments.getString(KEY_LOGIN_TYPE)
        configBeans = arguments.getParcelableArrayList(KEY_CONFIG)
        val size = configBeans?.size ?: 0
        for (i in 0 until size) {
            val bean: PopConfigBean = configBeans!![i] ?: continue
            if (bean.type == 1) {
                configBean = bean
            } else if (bean.type == 2) {
                floatConfigBean = bean
            }
        }
    }

    override fun initView(view: View?) {
        view?.let {
            publicPolicyTv = it.findViewById(getId("tv_public_policy"))
            warmTipTv = it.findViewById(getId("tv_warm_tip"))
            detailTv = it.findViewById(getId("tv_detail"))
            negativeBtn = it.findViewById(getId("dlg_btn_negative"))
            positiveBtn = it.findViewById(getId("dlg_btn_positive"))
            btnLineView = it.findViewById(getId("view_btn_line"))
        }
    }

    override fun setContent() {
        CbyLogUtils.i("chenby", configBean.toString())
        if (!TextUtils.isEmpty(configBean.content)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                publicPolicyTv.text = Html.fromHtml(
                    configBean.content,
                    Html.FROM_HTML_MODE_LEGACY
                )
            } else {
                publicPolicyTv.text = Html.fromHtml(configBean.content)
            }
        }
        if (configBean.tips != null && configBean.tips!!.isNotEmpty()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                warmTipTv.text = Html.fromHtml(
                    getListString(configBean.tips),
                    Html.FROM_HTML_MODE_LEGACY
                )
            } else {
                warmTipTv.text = Html.fromHtml(getListString(configBean.tips))
            }
            warmTipTv.visibility = View.VISIBLE
        } else {
            warmTipTv.visibility = View.GONE
        }
        if (configBean.linkBean != null && !TextUtils.isEmpty(configBean.linkBean!!.name) &&
            !TextUtils.isEmpty(configBean.linkBean!!.url)
        ) {
            detailTv.text = configBean.linkBean!!.name
            detailTv.visibility = View.VISIBLE
        } else {
            detailTv.visibility = View.GONE
        }
        if (configBean.buttonBeanList != null && configBean.buttonBeanList!!.isNotEmpty()) {
            negativeBtn.text = configBean.buttonBeanList!![0].name
        }
        if (configBean.buttonBeanList != null && configBean.buttonBeanList!!.size > 1) {
            positiveBtn.text = configBean.buttonBeanList!![1].name
            positiveBtn.visibility = View.VISIBLE
            btnLineView.visibility = View.VISIBLE
            negativeBtn.setBackgroundResource(
                getDrawableId("hykb_bg_default_dialog_left_btn")
            )
        } else {
            positiveBtn.visibility = View.GONE
            btnLineView.visibility = View.GONE
            negativeBtn.setBackgroundResource(
                getDrawableId("hykb_bg_default_dialog_single_btn")
            )
        }
    }

    private fun getListString(list: List<String>?): String {
        if (list == null) {
            return ""
        }
        val sb = StringBuilder()
        for (i in list.indices) {
            sb.append(list[i])
        }
        return sb.toString()
    }

    override fun initListener() {
        detailTv.setOnClickListener{
            if (configBean.linkBean != null
                && StringUtils.isValidHttpUrl(configBean.linkBean!!.url)
            ) {
                //用手机浏览器打开点击的链接
                configBean.linkBean!!.url?.let { it1 -> WebUtils.openUrl(activity, it1) }
            }
        }
        negativeBtn.setOnClickListener {
            if (configBean.buttonBeanList != null && configBean.buttonBeanList!!.isNotEmpty()) {
                configBean.buttonBeanList!![0].func?.let { it1 -> handleAction(it1) }
            }
        }
        positiveBtn.setOnClickListener {
            if (configBean.buttonBeanList != null && configBean.buttonBeanList!!.size > 1) {
                configBean.buttonBeanList!![1].func?.let { it1 -> handleAction(it1) }
            }
        }
    }

    private fun handleAction(action: String) {
        when (action) {
            ACTION_EXIT_GAME -> {
                // 退出游戏
                dismiss()
                AntiAddictManager.instance.handleEventBack(
                    CODE_LOGIN_EXIT_GAME,
                    STRING_EXIT_GAME_OR_LOGOUT)
            }
            ACTION_WSSFXX -> {
                if (FastClickUtils.isFastDoubleClick) {
                    return
                }
                // 完善身份信息
                openIdCardActivity()
            }
            ACTION_EXIT_POPUP -> {
                // 关闭弹窗后，再显示悬浮气泡
                floatConfigBean?.let {
                    AntiAddictManager.instance.showFcmFloat(it.content, it.linkBean)
                }
                AntiAddictManager.instance.handleEventBack(
                    CODE_LOGIN_ANTI_CLOSE,
                    "防沉迷弹窗的关闭")
                dismiss()
            }
        }
    }

    /**
     * 跳转到快爆完成实名认证
     */
    private fun openIdCardActivity() {
        if (!HykbAppUtils.checkHykbSupport(activity)) {
            AntiAddictManager.instance.openRealNameWeb(activity)
        } else {
            val intent = Intent("android.intent.action.VIEW").apply {
                putExtra(KEY_UID, uid)
                putExtra(KEY_NICK, nick)
                putExtra(KEY_LOGIN_TYPE, loginType)
                putExtra(KEY_APP_ID, SdkConfiguration.gameId)
                //固定字段
                putExtra("key", "loginsdk")
            }

            val componentName = ComponentName(
                HYKB_PACKAGE_NAME,
                "com.xmcy.hykb.app.ui.idcard.IdCardActivity"
            )
            intent.component = componentName
            startActivityForResult(intent, REQUEST_CODE_USER)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_USER && data != null) {
            val status: Boolean = data.getBooleanExtra("status", false)
            val msg: String? = data.getStringExtra("msg")
            CbyLogUtils.flog("m3839", "status = $status, msg = $msg")
            if (!status) {
                msg?.let {
                    activity.showToast(msg)
                }

                return
            }

            //重新拉取数据
            AntiAddictManager.instance.onBeat(AntiHeartManager.instance.currentSecond)
            dismiss()
        }
    }


    override fun layoutName(): String {
        return "anti_dialog_fragment"
    }

    companion object {
        /**
         * 用户实名认证的请求码
         */
        private const val REQUEST_CODE_USER = 1002

        /**
         * 好游快爆-包名
         */
        private const val HYKB_PACKAGE_NAME = "com.xmcy.hykb"
        const val KEY_CONFIG = "config"
        const val KEY_NICK = "nick"
        const val KEY_UID = "uid"
        const val KEY_LOGIN_TYPE = "platform"
        const val KEY_APP_ID = "app_id"

        fun show(
            activity: Activity,
            configBeans: List<PopConfigBean>,
            nick: String,
            uid: String,
            loginType: String
        ): BaseDialogFragment {
            val fragment = AntiDialogFragment()
            val data = Bundle().apply {
                putParcelableArrayList(KEY_CONFIG, configBeans as ArrayList<out Parcelable>?)
                putString(KEY_NICK, nick)
                putString(KEY_UID, uid)
                putString(KEY_LOGIN_TYPE, loginType)
            }
            fragment.arguments = data
            fragment.show(activity.fragmentManager, TAG_FRAGMENT_ANTI)
            return fragment
        }
    }
}